const fs = require('fs');
const path = require('path');
//
// part 1 - parse
//
var sFilePath = path.resolve("log.log");
var sLogs = fs.readFileSync(sFilePath, 'utf8');
// sLogs -> aLogs
var aLogs = null;
var oFileParseResult = { rows: [] };
var iCount = 0;
for (let i = 0; i < aLogs.length; i++) {
    const sLog = aLogs[i];
    var oLineParseResult = this.getLpRule().fnPaserLine(sLog, oFileParseResult);
    if (!oLineParseResult) {
        continue;
    }
    iCount++;
    oFileParseResult.rows.push(oLineParseResult);
}
var sLocSuffix = "run"
var sTargetFilePath = `${sFilePath}-${sLocSuffix}.json`;
fs.writeFileSync(sTargetFilePath, JSON.stringify(oFileParseResult));
//
// part 2 - calc
//
var oFileParseResult = JSON.parse(fs.readFileSync(sTargetFilePath, 'utf8'));
var sLocCalcName = "calc";
var mAggregate = {};
var oContext = {
    json: oFileParseResult,
    aggregation: mAggregate,
    rowId: 0
};
for (let i = 0; i < oFileParseResult.rows.length; i++) {
    oContext.rowId = i;
    // calc, entry, oContext -> kv
    var kv = null
    if (!mAggregate[kv.key]) {
        mAggregate[kv.key] = 0;
    }
    mAggregate[kv.key] = mAggregate[kv.key] + kv.value;
}
var sHeader = "";
var iCount = 0;
for (var prop in mAggregate) {
    var sLine = prop + "," + mAggregate[prop];
    iCount++;
    sHeader += sLine + "\n";
}
fs.writeFileSync(`${sTargetFilePath}-${sLocCalcName}.csv`, sHeader);